/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var ItbActivityModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  /**
   * `act_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '活动id',
   * `type` int(3) NOT NULL DEFAULT '10' COMMENT '活动分类: 10:秒杀活动',
   * `title` text NOT NULL COMMENT '活动标题',
   * `start_time` datetime NOT NULL COMMENT '''有效期开始日时'',三种状态：10未开场（当前时间<开始时间）、20已开场（结束时间>当前时间>=开始时间）、30已结束（当前时间>=结束时间）',
   * `end_time` datetime NOT NULL COMMENT '有效期结束日时',
   * `desc` text COMMENT '活动备注',
   * `image` text COMMENT '活动备图',
   * `url` text COMMENT '链接（预留）',
   * `order` int(3) NOT NULL DEFAULT '999' COMMENT '排序',
   * `publish` int(1) NOT NULL DEFAULT '0' COMMENT '发布状态: 0未发布, 1发布',
   * `create_time` datetime NOT NULL,
   * `update_time` datetime NOT NULL,
   * `update_by` varchar(50) DEFAULT NULL,
   * `del_flg` int(1) NOT NULL DEFAULT '0',
   *
   * */
};
ItbActivityModel.prototype = new ItbBaseModel();

// 取得表名
ItbActivityModel.prototype.getTableName = function(){
    return 'itb_activity';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbActivityModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'act_id='+this.act_id;
};
//------------------------------------------------------------------

//------------------------------------------------------------------
ItbActivityModel.prototype.getActInfoById = function(actId, callback) {

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbActivityModel.getActInfoById Err:'+err);
            return callback(err, null);
        }

        var sql = " SELECT t.*, "+
            " UNIX_TIMESTAMP(t.start_time) AS ts_start_time, "+
            " UNIX_TIMESTAMP(t.end_time) AS ts_end_time "+
            " FROM itb_activity t "+
            " WHERE t.del_flg=0 AND t.act_id="+actId;

        console.log(sql);
        connection.query(sql, function (error, result) {
            connection.release();
            console.log();

            if(result && result.length>0) {
                return callback(error, result[0]);
            } else {
                return callback(error, null);
            }
        });
    });
};

/**
 * 获取已发布的秒杀活动
 * @param callback
 *          error 错误原因
 *          activitys 已发布的活动列表
 * */
ItbActivityModel.prototype.getPublishActivitys = function(callback) {

    pool.pool.getConnection(function(err, connection) {
        var sql = "SELECT * FROM itb_activity a WHERE a.type=10 AND a.publish =1 AND SYSDATE() < a.end_time AND a.del_flg=0 ORDER BY a.order";

        console.log(sql);
        connection.query(sql, function (error, result) {
            connection.release();
            console.log();

            callback(error, result);
        });
    });
};

// 导出
module.exports = ItbActivityModel;